<template>
  <div class="photo-detail-page">
    <AppHeader />
    <div class="photo-detail-container">
      <!-- 返回按钮 -->
      <div class="back-button">
        <el-button @click="goBack" :icon="ArrowLeft">返回</el-button>
      </div>
      
      <div class="photo-detail-content" v-if="photo">
        <!-- 左侧：照片展示 -->
        <div class="photo-display">
          <div class="photo-container">
            <img 
              :src="photoPreviewUrl" 
              :alt="photo.file_name"
              @load="handleImageLoad"
              @error="handleImageError"
            />
            <div class="photo-loading" v-if="imageLoading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>加载中...</span>
            </div>
          </div>
          
          <!-- 照片操作工具栏 -->
          <div class="photo-actions">
            <el-button-group>
              <el-button @click="openInFolder" :icon="FolderOpened">在文件夹中显示</el-button>
              <el-button @click="openWithDefaultApp" :icon="Monitor">使用默认应用打开</el-button>
              <el-button @click="downloadPhoto" :icon="Download">下载</el-button>
            </el-button-group>
            
            <el-button-group class="ml-4">
              <el-button @click="rotateLeft" :icon="RefreshLeft">向左旋转</el-button>
              <el-button @click="rotateRight" :icon="RefreshRight">向右旋转</el-button>
            </el-button-group>
            
            <div class="rating-container">
              <span>评分：</span>
              <el-rate 
                v-model="photo.rating" 
                @change="updateRating"
                :max="5"
                show-score
              />
            </div>
          </div>
        </div>
        
        <!-- 右侧：照片信息和编辑 -->
        <div class="photo-info">
          <el-tabs v-model="activeTab">
            <!-- 基本信息 -->
            <el-tab-pane label="基本信息" name="basic">
              <div class="info-section">
                <div class="info-item">
                  <label>文件名：</label>
                  <span>{{ photo.file_name }}</span>
                </div>
                <div class="info-item">
                  <label>文件路径：</label>
                  <span class="file-path" :title="photo.file_path">{{ photo.file_path }}</span>
                </div>
                <div class="info-item">
                  <label>文件大小：</label>
                  <span>{{ formatFileSize(photo.file_size) }}</span>
                </div>
                <div class="info-item">
                  <label>尺寸：</label>
                  <span>{{ photo.width }} × {{ photo.height }}</span>
                </div>
                <div class="info-item">
                  <label>格式：</label>
                  <span>{{ photo.format }}</span>
                </div>
                <div class="info-item">
                  <label>创建时间：</label>
                  <span>{{ formatDate(photo.created_at) }}</span>
                </div>
                <div class="info-item">
                  <label>修改时间：</label>
                  <span>{{ formatDate(photo.modified_at) }}</span>
                </div>
                <div class="info-item" v-if="photo.captured_at">
                  <label>拍摄时间：</label>
                  <span>{{ formatDate(photo.captured_at) }}</span>
                </div>
              </div>
            </el-tab-pane>
            
            <!-- EXIF信息 -->
            <el-tab-pane label="EXIF信息" name="exif">
              <div class="info-section">
                <div class="info-item" v-if="photo.camera_make">
                  <label>相机品牌：</label>
                  <span>{{ photo.camera_make }}</span>
                </div>
                <div class="info-item" v-if="photo.camera_model">
                  <label>相机型号：</label>
                  <span>{{ photo.camera_model }}</span>
                </div>
                <div class="info-item" v-if="photo.latitude && photo.longitude">
                  <label>GPS位置：</label>
                  <span>{{ photo.latitude }}, {{ photo.longitude }}</span>
                  <el-button 
                    type="text" 
                    @click="openMap" 
                    class="ml-2"
                  >
                    查看地图
                  </el-button>
                </div>
                <div class="info-item" v-if="photo.altitude">
                  <label>海拔：</label>
                  <span>{{ photo.altitude }}米</span>
                </div>
              </div>
            </el-tab-pane>
            
            <!-- 描述和标签 -->
            <el-tab-pane label="描述和标签" name="tags">
              <div class="info-section">
                <div class="description-section">
                  <label>描述：</label>
                  <el-input
                    v-model="photoDescription"
                    type="textarea"
                    :rows="4"
                    placeholder="添加照片描述..."
                    @blur="updateDescription"
                  />
                </div>
                
                <div class="tags-section">
                  <label>标签：</label>
                  <div class="tags-container">
                    <el-tag
                      v-for="tag in photoTags"
                      :key="tag.id"
                      :color="tag.color"
                      closable
                      @close="removeTag(tag.id)"
                      class="photo-tag"
                    >
                      {{ tag.name }}
                    </el-tag>
                    
                    <el-autocomplete
                      v-model="newTag"
                      :fetch-suggestions="queryTags"
                      placeholder="添加标签..."
                      @select="addTag"
                      @keyup.enter="addNewTag"
                      class="tag-input"
                    />
                  </div>
                </div>
              </div>
            </el-tab-pane>
            
            <!-- 相册 -->
            <el-tab-pane label="相册" name="albums">
              <div class="info-section">
                <div class="albums-section">
                  <label>所属相册：</label>
                  <div class="albums-container">
                    <el-tag
                      v-for="album in photoAlbums"
                      :key="album.id"
                      closable
                      @close="removeFromAlbum(album.id)"
                      class="album-tag"
                    >
                      {{ album.name }}
                    </el-tag>
                    
                    <el-dropdown @command="addToAlbum">
                      <el-button type="primary" plain>
                        添加到相册<el-icon class="el-icon--right"><arrow-down /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item 
                            v-for="album in availableAlbums"
                            :key="album.id"
                            :command="album.id"
                          >
                            {{ album.name }}
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div v-else-if="loading" class="photo-loading-container">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>加载照片详情中...</span>
      </div>
      
      <!-- 错误状态 -->
      <div v-else class="photo-error-container">
        <el-result
          icon="error"
          title="加载失败"
          sub-title="无法加载照片详情，请稍后重试"
        >
          <template #extra>
            <el-button type="primary" @click="goBack">返回</el-button>
          </template>
        </el-result>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  ArrowLeft, 
  FolderOpened, 
  Monitor, 
  Download, 
  RefreshLeft, 
  RefreshRight,
  Loading,
  ArrowDown
} from '@element-plus/icons-vue'
import { usePhotoStore } from '../stores/photo'
import { useAlbumStore } from '../stores/album'
import { useSearchStore } from '../stores/search'
import type { Photo } from '../types/photo'
import type { Tag } from '../types/common'
import type { Album } from '../types/album'
import AppHeader from '../components/common/AppHeader.vue'
import { formatDate, formatFileSize } from '../utils/date'

// 导入全局类型
import '../types/global'

const route = useRoute()
const router = useRouter()
const photoStore = usePhotoStore()
const albumStore = useAlbumStore()
const searchStore = useSearchStore()

// 状态
const loading = ref(true)
const imageLoading = ref(false)
const activeTab = ref('basic')
const photoDescription = ref('')
const newTag = ref('')
const photoTags = ref<Tag[]>([])
const photoAlbums = ref<Album[]>([])

// 计算属性
const photo = computed(() => photoStore.currentPhoto)
const photoId = computed(() => route.params.id as string)
const photoPreviewUrl = computed(() => {
  if (!photo.value) return ''
  // 这里应该使用预览图URL，暂时使用缩略图
  return photo.value.thumbnail_path || ''
})

const availableAlbums = computed(() => {
  return albumStore.albums.filter(album => 
    !photoAlbums.value.some(photoAlbum => photoAlbum.id === album.id)
  )
})

// 生命周期钩子
onMounted(async () => {
  await loadPhotoDetail()
})

// 监听照片ID变化
watch(photoId, async () => {
  if (photoId.value) {
    await loadPhotoDetail()
  }
})

// 加载照片详情
const loadPhotoDetail = async () => {
  if (!photoId.value) return
  
  loading.value = true
  
  try {
    // 获取照片详情
    await photoStore.getPhotoById(parseInt(photoId.value))
    
    if (photo.value) {
      // 初始化描述
      photoDescription.value = photo.value.description || ''
      
      // 获取照片标签
      await loadPhotoTags()
      
      // 获取照片相册
      await loadPhotoAlbums()
    }
  } catch (error) {
    console.error('加载照片详情失败:', error)
    ElMessage.error('加载照片详情失败')
  } finally {
    loading.value = false
  }
}

// 加载照片标签
const loadPhotoTags = async () => {
  // 这里应该调用获取照片标签的API
  // 暂时使用空数组
  photoTags.value = []
}

// 加载照片相册
const loadPhotoAlbums = async () => {
  // 这里应该调用获取照片相册的API
  // 暂时使用空数组
  photoAlbums.value = []
}

// 图片加载处理
const handleImageLoad = () => {
  imageLoading.value = false
}

const handleImageError = () => {
  imageLoading.value = false
  ElMessage.error('图片加载失败')
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 打开文件夹
const openInFolder = async () => {
  if (!photo.value) return
  
  try {
    await photoStore.openInFolder(photo.value.file_path)
  } catch (error) {
    console.error('打开文件夹失败:', error)
    ElMessage.error('打开文件夹失败')
  }
}

// 使用默认应用打开
const openWithDefaultApp = async () => {
  if (!photo.value) return
  
  try {
    await photoStore.openWithDefaultApp(photo.value.file_path)
  } catch (error) {
    console.error('打开文件失败:', error)
    ElMessage.error('打开文件失败')
  }
}

// 下载照片
const downloadPhoto = () => {
  if (!photo.value) return
  
  // 创建下载链接
  const link = document.createElement('a')
  link.href = photoPreviewUrl.value
  link.download = photo.value.file_name
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 旋转图片
const rotateLeft = async () => {
  // 这里应该调用旋转图片的API
  ElMessage.info('向左旋转功能待实现')
}

const rotateRight = async () => {
  // 这里应该调用旋转图片的API
  ElMessage.info('向右旋转功能待实现')
}

// 更新评分
const updateRating = async (rating: number) => {
  if (!photo.value) return
  
  try {
    await photoStore.updatePhoto(photo.value.id, { rating })
    ElMessage.success('评分已更新')
  } catch (error) {
    console.error('更新评分失败:', error)
    ElMessage.error('更新评分失败')
  }
}

// 更新描述
const updateDescription = async () => {
  if (!photo.value) return
  
  try {
    await photoStore.updatePhoto(photo.value.id, { description: photoDescription.value })
    ElMessage.success('描述已更新')
  } catch (error) {
    console.error('更新描述失败:', error)
    ElMessage.error('更新描述失败')
  }
}

// 查询标签建议
const queryTags = async (queryString: string, cb: (arg: any[]) => void) => {
  if (!queryString) {
    cb([])
    return
  }
  
  try {
    // 这里应该调用搜索标签的API
    // 暂时返回热门标签
    const suggestions = searchStore.popularTags
      .filter(tag => tag.name.toLowerCase().includes(queryString.toLowerCase()))
      .map(tag => ({ value: tag.name, item: tag }))
    
    cb(suggestions)
  } catch (error) {
    console.error('查询标签失败:', error)
    cb([])
  }
}

// 添加标签
const addTag = async (tag: any) => {
  if (!photo.value || !tag) return
  
  try {
    // 这里应该调用添加标签的API
    const newTagItem: Tag = {
      id: tag.id || Date.now(),
      name: tag.value || tag.name,
      color: tag.color || '#409EFF'
    }
    
    photoTags.value.push(newTagItem)
    newTag.value = ''
    
    ElMessage.success('标签已添加')
  } catch (error) {
    console.error('添加标签失败:', error)
    ElMessage.error('添加标签失败')
  }
}

// 添加新标签
const addNewTag = async () => {
  if (!photo.value || !newTag.value.trim()) return
  
  try {
    // 这里应该调用创建标签的API
    const newTagItem: Tag = {
      id: Date.now(),
      name: newTag.value.trim(),
      color: '#409EFF'
    }
    
    photoTags.value.push(newTagItem)
    newTag.value = ''
    
    ElMessage.success('标签已添加')
  } catch (error) {
    console.error('添加标签失败:', error)
    ElMessage.error('添加标签失败')
  }
}

// 移除标签
const removeTag = async (tagId: number) => {
  if (!photo.value) return
  
  try {
    // 这里应该调用移除标签的API
    photoTags.value = photoTags.value.filter(tag => tag.id !== tagId)
    ElMessage.success('标签已移除')
  } catch (error) {
    console.error('移除标签失败:', error)
    ElMessage.error('移除标签失败')
  }
}

// 添加到相册
const addToAlbum = async (albumId: number) => {
  if (!photo.value) return
  
  try {
    // 这里应该调用添加到相册的API
    const album = albumStore.albums.find(a => a.id === albumId)
    if (album) {
      photoAlbums.value.push(album)
      ElMessage.success(`已添加到相册 "${album.name}"`)
    }
  } catch (error) {
    console.error('添加到相册失败:', error)
    ElMessage.error('添加到相册失败')
  }
}

// 从相册移除
const removeFromAlbum = async (albumId: number) => {
  if (!photo.value) return
  
  try {
    // 这里应该调用从相册移除的API
    const album = photoAlbums.value.find(a => a.id === albumId)
    if (album) {
      photoAlbums.value = photoAlbums.value.filter(a => a.id !== albumId)
      ElMessage.success(`已从相册 "${album.name}" 移除`)
    }
  } catch (error) {
    console.error('从相册移除失败:', error)
    ElMessage.error('从相册移除失败')
  }
}

// 打开地图
const openMap = () => {
  if (!photo.value || !photo.value.latitude || !photo.value.longitude) return
  
  const url = `https://maps.google.com/?q=${photo.value.latitude},${photo.value.longitude}`
  window.open(url, '_blank')
}
</script>

<style scoped>
.photo-detail-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.photo-detail-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: var(--el-bg-color-page);
}

.back-button {
  margin-bottom: 20px;
}

.photo-detail-content {
  display: flex;
  gap: 20px;
  min-height: calc(100vh - 120px);
}

/* 照片展示区域 */
.photo-display {
  flex: 2;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.photo-container {
  position: relative;
  background-color: var(--el-fill-color-lighter);
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 500px;
}

.photo-container img {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

.photo-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 16px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
}

.photo-actions {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16px;
}

.rating-container {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: auto;
}

/* 照片信息区域 */
.photo-info {
  flex: 1;
  background-color: var(--el-bg-color);
  border-radius: 8px;
  padding: 20px;
  box-shadow: var(--el-box-shadow-light);
}

.info-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.info-item label {
  font-weight: 500;
  min-width: 100px;
  flex-shrink: 0;
}

.file-path {
  word-break: break-all;
}

.description-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tags-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.photo-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.tag-input {
  width: 200px;
}

.albums-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.albums-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.album-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

/* 加载和错误状态 */
.photo-loading-container,
.photo-error-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 50vh;
  gap: 16px;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .photo-detail-content {
    flex-direction: column;
  }
  
  .photo-display,
  .photo-info {
    flex: 1;
  }
}
</style>